package lei.l_存储文件;

import com.alibaba.fastjson.JSON;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * @className: main1
 * @author: xl
 * @date: 2025/7/26 15:03
 * @Version: 1.0
 * @description:
 */

public class main1 {


    //使用NIO.2 (推荐)
    public void saveFileWithNIO(String content, String filePath) {
        try {
            Files.write(Paths.get(filePath), content.getBytes(),
                    StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //


    //存储二进制文件（如图片、音频等）
    public void saveBinaryFile(byte[] data, String filePath) {
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //存储文本文件
    public void saveTextFile(String content, String filePath) {
        try (FileWriter writer = new FileWriter(filePath)) {
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //使用Files工具类（Java 8+）
    // 存储多行文本
    public static void saveLinesToFile(List<String> lines, String filePath) {
        try {
            Files.write(Paths.get(filePath), lines);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 使用BufferedWriter提高性能
    public void saveFileWithBuffer(String content, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    //存储Properties文件
    public void savePropertiesFile() {
        Properties props = new Properties();
        props.setProperty("key1", "value1");
        props.setProperty("key2", "value2");

        try (FileOutputStream fos = new FileOutputStream("config.properties")) {
            props.store(fos, "配置文件注释");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 存储JSON到文件
    public void saveJsonToFile(Object obj, String filePath) {
        try {
            String jsonString = JSON.toJSONString(obj, true); // 格式化输出
            Files.write(Paths.get(filePath), jsonString.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        // 使用示例
        List<String> lines = Arrays.asList("第一行", "第二行", "第三行");
        saveLinesToFile(lines, "output.txt");
    }


}

